// pages2/pages/index/beeperVillageCode/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
const $api = require('../../../../request/api').API;
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    villageId: '',
    content: '',
    villageName: '',
    // address:"",
    introduce: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let scene = decodeURIComponent(options.scene);
    if (scene != 'undefined') {
      this.setData({
        villageId: scene.split('vid=')[1]
      });
      if (wx.getStorageSync(Storage.USER_OPEN_ID)) {
        this.isLogin();
      } else {
        app.openIdCallback = openId => {
          if (openId) {
            this.isLogin();
          }
        };
      }
    } else if (app.globalData.villageId) {
      this.setData({
        villageId: app.globalData.villageId
      });
      delete app.globalData.villageId;
      this.getVillageInfo();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},
  // 判断用户是否登录，登录就会获取小区信息
  isLogin() {
    const token = wx.getStorageSync(Storage.ACCESS_TOKEN);
    if (token) {
      this.getVillageInfo();
    } else {
      app.globalData.villageId = this.data.villageId;
      wx.reLaunch({
        url: '/subcontract/person/pages/login/login/index'
      });
    }
  },
  async getVillageInfo() {
    const res = await $api.getVillageDetail({ id: this.data.villageId });
    const { villageName, introduce } = res.data.data;
    // let val = provinceName+cityName
    // if(areaName)val = val+areaName
    // if(streetName)val = val+streetName
    // if(address)val = val+address
    this.setData({
      villageName,
      introduce
    });
  },
  handleInput(e) {
    this.setData({
      content: e.detail.value
    });
  },
  // 提交
  submit() {
    const { villageId, content } = this.data;
    if (!content) {
      Toast.fail('请输入房号');
      return;
    }
    Dialog.confirm({
      title: '提示',
      message: '确认绑定？'
    })
      .then(() => {
        $api
          .bindingByLinkCode({ id: villageId, content, state: 1 })
          .then(res => {
            app.globalData.beeperId = res.data.data;
            Toast.success({
              message: '绑定成功',
              forbidClick: true
            });
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/home/index'
              });
            }, 1500);
          })
          .catch(err => {});
      })
      .catch(() => {
        // on cancel
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
